<template>
  <div style="display:flex;position: relative;" v-loading="loading2">
    <el-button :disabled="loading2" type="text" style="position: absolute;top: 0;right: 0;z-index: 99999999;" icon="el-icon-circle-plus-outline" class="cursor_pointer" @click="addHanlder">Add</el-button>
    <el-tabs v-if="FatheractiveName === 'assetsscope'" lazy v-model="activeName" @tab-click="handleClick" style="width:100%">
      <el-tab-pane :name="key" v-for="(list,key) in assetsFilter(assets)" :key="key">
        <template v-slot:label>
          <span>{{ key }}</span>
          <ZTag :type="'blue'"
              round
              size="mini"
              style="margin-left: 4px">
          {{ list.length }}
        </ZTag>
        </template>
        <div style="display: flex;justify-content: flex-end;">
          <el-input placeholder="Search"
                    style="width:280px;margin-bottom: 10px;float: right;"
                    prefix-icon="el-icon-search"
                    clearable
                    @input="keyWordsChange($event, key)"
                    v-model="assetsKey[key]">
          </el-input>
        </div>
        <RecycleScroller
            class="scroller"
            :items="list"
            :item-size="48"
            :style="{ height: '600px' }"
            v-if="list.length"
            v-slot="{ item, index }"
          >
              <div style="display:flex;height: 48px;justify-content: space-between;border: 1px solid #ccc;border:1px solid #ccc;padding-left: 6px;width:calc(100% - 1px)" :style="{'border-bottom': index!==list.length-1?0:'1px solid #ccc'}">
                <div style="width:calc(100% - 48px);display: flex;flex-direction: column;justify-content: center;" >
                  <ZTooltip :content="item.resourceName"
                            :line="1"
                            placement="top">
                    <span style="font-weight: 700;font-size: 14px;">
                      {{ item.resourceName }}
                    </span>
                  </ZTooltip >
                  <ZTooltip style="margin-top:3px;" :content="item.description"
                          :line="1"
                          placement="top">
                  <span style="font-size: 12px;color: #909399;">
                    {{ item.description }}
                  </span>
                </ZTooltip>
              </div>
              <div class="el-icon-close cursor_pointer delete_icon" style="font-size: 20px;width: 45px;line-height: 45px;text-align: center;" @click="deleteItem(item,key)"></div>

              </div>
          </RecycleScroller>

      </el-tab-pane>
    </el-tabs>
    <b-dashboard-add-widget v-model="assets[activeName]"
                              title="Assets Permission"
                              :customize="false"
                              :internalWidget="false"
                              :internalSlicer="false"
                              :device="false"
                              :tab="tab"
                              :widget="isWidget"
                              :slicer="isSlicer"
                              :scorecardList="isScorecard"
                              :dashboard="isDashboard"
                              :dataset="isDataset"
                              :bot="isBot"
                              :isAssetsModel="isAssetsModel"
                              rootBusinessType="Custom"
                              :visible.sync="gadgetChoiceModalVisible" @select-list="selectDashboard">
                            </b-dashboard-add-widget>
  </div>
</template>
<script>
import { debounce } from 'lodash'
import ZTooltip from '@/components/storybook/z-tooltip'
import ZTag from '@/components/storybook/z-tag'
import BDashboardAddWidget from '@/components/storybook/b-dashboard-add-widget/index'
// import { isSlicer } from '@/components/storybook/hooks/useGadget'
export default {
  components: {
    ZTooltip,
    ZTag,
    BDashboardAddWidget
  },
  name: 'AssetsScope',
  provide () {
    return {
      isAssetsModel: () => this.isAssetsModel
    }
  },
  inject:{isDefaultRole: {default:false}},
  props: {
    FatheractiveName: {
      type: String,
      default: ''
    },
    loading2: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: String,
      default: ''
    },
    isDisabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      activeName: 'Dashboards',
      searchKeyWords: '',
      gadgetChoiceModalVisible: false,
      isAssetsModel: true,
      assets:{
        Dashboards:[],
        Widgets:[],
        Dataset:[],
        Bots:[],
        Scorecards:[],
        Slicer:[]
      },
      assetsKey: {
        Dashboards:'',
        Widgets:'',
        Dataset:'',
        Bots:'',
        Scorecards:'',
        Slicer:''
      },
      assetsKeyValue: {
        Dashboards:'',
        Widgets:'',
        Dataset:'',
        Bots:'',
        Scorecards:'',
        Slicer:''
      },
      isWidget: false,
      isSlicer: false,
      isScorecard: false,
      isDashboard: false,
      isDataset: false,
      isBot: false,
      tab: 'dashboard',
      oldAssets: {
        Dashboards:[],
        Widgets:[],
        Dataset:[],
        Bots:[],
        Scorecards:[],
        Slicer:[]
      }
    }
  },
  methods: {
    init (roleId) {
      console.log('roleId',roleId)
      if(!roleId) return
      this.$emit('update:loading2',true)
      let params = {
        roleId,
        defaultOnly: this.isDefaultRole&&this.isDefaultRole()
      }
      this.$interface.system.getRoleAssets(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        for(var key in this.assets) {
          this.assets[key] = res.data[key] || []
        }
        this.oldAssets = JSON.parse(JSON.stringify(this.assets))
      }).catch(() => { })
      .finally(() => {
        this.$emit('update:loading2',false)
      })

    },
    // reset() {
    //   Object.assign(this.$data, this.$options.data()) 
    // },
    getValue() {
      
      let temp = {
        Dashboards:{addList:[],deleteList:[]},
        Widgets:{addList:[],deleteList:[]},
        Dataset:{addList:[],deleteList:[]},
        Bots:{addList:[],deleteList:[]},
        Scorecards:{addList:[],deleteList:[]},
        Slicer:{addList:[],deleteList:[]}
      }
      for(var key1 in this.assets) {
        this.assets[key1].forEach(item => {
          let index = this.oldAssets[key1].findIndex(oldItem => oldItem.resourceId === item.resourceId)
          if(index === -1) {
            temp[key1].addList.push(item)
          }
        })
      }
      for(var key2 in this.oldAssets) {
        this.oldAssets[key2].forEach(item => {
          let index = this.assets[key2].findIndex(oldItem => oldItem.resourceId === item.resourceId)
          if(index === -1) {
            temp[key2].deleteList.push(item)
          }
        })
      }
      for(var key3 in temp){
        temp[key3].addList = temp[key3].addList.map(item => {
          return {
            resourceId: item.resourceId,
            businessType: item.businessType
          }
        })
        temp[key3].deleteList = temp[key3].deleteList.map(item => {
          return {
            resourceId: item.resourceId,
            businessType: item.businessType,
            id: item.id
          }
        })
      }
      return temp
    },
    clickHanlder(val) {
      this.activeName = val
    },
    handleClick(tab) {
      this.assetsKey = {
        Dashboards:'',
        Widgets:'',
        Dataset:'',
        Bots:'',
        Scorecards:'',
        Slicer:''
      }
      this.assetsKeyValue = {
        Dashboards:'',
        Widgets:'',
        Dataset:'',
        Bots:'',
        Scorecards:'',
        Slicer:''
      }
    },
    selectDashboard(list) {
    },
    addHanlder() {
      this.isWidget = false
      this.isSlicer = false
      this.isScorecard = false
      this.isDashboard = false
      this.isDataset = false
      this.isBot = false
      this.Slicer = false
      if(this.activeName === 'Dashboards') {
        this.isDashboard = true
        this.tab = 'dashboard'
      } else if(this.activeName === 'Widgets') {
        this.isWidget = true
        this.tab = 'widget'
      } else if(this.activeName === 'Dataset') {
        this.isDataset = true
        this.tab = 'dataset'
      } else if(this.activeName === 'Bots') {
        this.isBot = true
        this.tab = 'bot'
      } else if(this.activeName === 'Scorecards') {
        this.isScorecard = true
        this.tab = 'scorecard'
      } else if(this.activeName === 'Slicer') {
        this.isSlicer = true
        this.tab = 'slicer'
      }
      this.gadgetChoiceModalVisible = true
    },
    deleteItem(ii,key) {
      let index = this.assets[key].findIndex(item => item.resourceId === ii.resourceId)
      this.assets[key].splice(index, 1)
    },
    keyWordsChange: debounce(function(val, key) {
      const normalizedVal = val.trim()
      this.assetsKeyValue[key] = normalizedVal
    }, 1000),
    assetsFilter (assets) {
      let obj = JSON.parse(JSON.stringify(assets))
      for (var key in obj) {
        try {
          
          obj[key] = obj[key].filter(item => item?.resourceName?.toLowerCase()?.includes(this.assetsKeyValue[key].toLowerCase()))
        } catch (error) {
          
        }
      }
      return obj
    }
  },
  created () {
    this.init(this.roleId)
  },
  watch: {
    assetsKey: {
      handler(val) {
        let temp = false
        for(var key in val) {
          if(val[key].trim()) {
            temp = true
          }
        }
        this.$emit('update:isDisabled',temp)
      },
      deep: true,
      immediate: true
    },
  }
}
</script>
<style scoped>
::v-deep .el-tabs__content {
  height: 645px;
}
.delete_icon:hover {
  color: #17B3A3;
}
</style>
